import { _decorator, assert, Asset, AssetManager, assetManager, AudioClip, Component, Constructor, Node, Prefab, SpriteFrame } from 'cc';
import { SpriteFramesCfg } from '../../../auto/SpriteFramesCfg';

export class ResManager {
    // private static _instance: ResManager = null!;
    // /** 获取单例的接口 */
    // static getInstance() {
    //     if (this._instance === null) {
    //         this._instance = new ResManager();
    //     }
    //     return this._instance;
    // }

    // private constructor() {
    //     // 私有化的构造函数
    // }

    // loadPrefab(bundleName: string, prefabPath: string, cb: (prefab: Prefab | null) => void) {
    //     assetManager.loadBundle(bundleName, (e, bundle) => {
    //         bundle.load(prefabPath, Prefab, (err, prefab: Prefab) => {
    //             if (err) {
    //                 console.error(err);
    //                 cb(null);
    //                 return;
    //             }
    //             cb(prefab)
    //         })
    //     })
    // }


    // loadAudioClip(bundleName:string,audioPath:string,cb:(asset:AudioClip|null) => void){
    //     assetManager.loadBundle(bundleName,(e,bundle) =>{
    //         bundle.load(audioPath,AudioClip,(err,assert:AudioClip) =>{
    //             if(err){
    //                 console.error(err);
    //                 cb(null);
    //                 return;
    //             }
    //             cb(assert)

    //         })
    //     })
    // }

    loadBundle(bundleName: string, cb?: (bundle: AssetManager.Bundle | null) => void) {
        assetManager.loadBundle(bundleName, (e, bundle) => {
            cb && cb(bundle);
        });
    }


    loadBundleAsync(bundleName: string): Promise<AssetManager.Bundle> {
        return new Promise<AssetManager.Bundle>(rs => {
            this.loadBundle(bundleName, rs);
        })
    }

    // loadPrefabByBUrl(bUrl: IBundleUrl, cb: (prefab: Prefab | null) => void) {
    //     this.loadPrefab(bUrl.b, bUrl.l, cb);
    // }

    // loadAudioByBUrl(bUrl: IBundleUrl, cb: (audioClip: AudioClip | null) => void) {
    //     this.loadAudioClip(bUrl.b, bUrl.l, cb);
    // }

    loadAsset<T extends Asset>(bUrl: IBundleUrl, type: Constructor<T> | null, cb: (asset: T | null) => void) {
        assetManager.loadBundle(bUrl.b, (e, bundle) => {
            bundle.load(bUrl.l, type, (err, _asset) => {
                if (err) {
                    console.error(err);
                    return cb(null);
                }
                cb(_asset);
            })
        })
    }


    loadAssetAsync<T extends Asset>(bUrl: IBundleUrl, type: Constructor<T> | null) {
        return new Promise<T>(rs => this.loadAsset(bUrl, type, rs as any))
    }

    getAsset<T extends Asset>(bUrl: IBundleUrl, type?: Constructor<T> | null): T {
        let assetBundle = assetManager.getBundle(bUrl.b);
        return assetBundle.get(bUrl.l,type);
    }



}


